<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        title="报废出库单明细"
        :needOperateAffair="true"
        :needReturn="!$route.query.processInstanceId"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="
              $permission('scrapExportOrder:print') &&
              infoList.data.status !== 1
            "
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button
            v-if="
              $permission('scrapExportOrder:print') &&
              infoList.data.status !== 1
            "
            @click="print"
            >打印</el-button
          > -->
          <el-button
            v-if="
              $permission('scrapExportOrder:exportExcel') &&
              infoList.data.status !== 1
            "
            @click="exportExcel"
            >导出excel</el-button
          >
            
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="cancelAudit" @click="handleCancelAudit">销审</el-button>
          <el-button v-if="canRevoke" @click="revoke">撤回</el-button>
          <el-button v-if="canCancel" @click="doCancel">取消</el-button>
          <el-button v-if="canCancelDownTransfer" @click="cancelDownTransfer"
            >取消拣货</el-button
          >
          <el-button v-if="canExecute" @click="scrapExport">出库</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList" />
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <scrap-export-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :orderId="modifyInfo.orderId"
    />
    <individual-details
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :query="individualInfo.query"
      :info="individualInfo.info"
    />
  </div>
</template>

<script setup name="scrapExportOrderDetail">
import {
  detailScrapExportOrder,
  exportExcelScrapExportOrder,
  getScrapExportOrderDetailCustomizeListAll,
  getScrapExportPrint,
  submitScrapExportOrder,
  executeScrapExportOrder,
  revokeScrapExportOrder,
  scrapExportOrdersCancel,
  scrapExportOrdersCancelDownShelf,
  scrapExportOrderscancelAudit
} from '@/api/stock.js'
import { getCustomizeSetting } from '@/api/customize'
import { orderAffairAll } from '@/api/affair'
import ScrapExportOrderModify from './modify'
import { fatchTemplateByCode } from '@/api/base'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const BasicInformation = defineAsyncComponent(() =>
  import('@/components/BasicInformation/index')
)
const PageTable = defineAsyncComponent(() =>
  import('@/components/PageTable/index')
)
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const IndividualDetails = defineAsyncComponent(() =>
  import('./IndividualDetails')
)
const props = defineProps(['visible', 'tableRow', 'id'])

const infoList = reactive({
  data: {},
  fieldList: [
    { label: '出库单号', value: 'orderNo', type: 'text' },
    { label: '出库仓库', value: 'depotName', type: 'text' },
    { label: '出库部门', value: 'deptName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '出库人', value: 'exportUserName', type: 'text' },
    { label: '出库时间', value: 'exportTime', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'text' },
  ],
})
console.log(props)
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRow ? props.tableRow ? props.tableRow.id : props.id : props.id,
      },
    },
    queryParams: {},
  },
})
const modifyInfo = reactive({
  visible: false,
  title: '',
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: showDetail,
        show: proxy.$permission('scrapExportOrder:IndividualDetails'),
        ifRender: ifIndividualDetails,
      },
    ],
  },
})
const affairTableInfo = reactive({
  query: {
    orderType: 10,
    orderId: props.tableRow ? props.tableRow ? props.tableRow.id : props.id : props.id,
    sort: 'operate_time desc',
  },
})
const individualInfo = reactive({
  visible: false,
  query: {},
  info: {},
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canUpdate = computed(() => {
  return (
    proxy.$permission('scrapExportOrder:update') && (infoList.data.status === 1 || infoList.data.status === 8)
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('scrapExportOrder:submit') && (infoList.data.status === 1 || infoList.data.status === 8)
  )
})
const cancelAudit = computed(() => {
  return (
    proxy.$permission('scrapExportOrder:cancelAudit') && infoList.data.status === 3 &&
    proxy.$store.state.permission.systemConfig.allow_scrap_export_approval != 0
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('scrapExportOrder:revoke') &&
    (infoList.data.status === 6 || (infoList.data.status === 3 && proxy.$store.state.permission.systemConfig.allow_scrap_export_approval == 0))
    // && infoList.data.isCargoSpaceManage === 0
  )
})
const canCancel = computed(() => {
  return (
    proxy.$permission('scrapExportOrder:cancel') && infoList.data.status === 3
  )
})
const canCancelDownTransfer = computed(() => {
  return (
    proxy.$permission('scrapExportOrder:cancelDown') &&
    infoList.data.status === 4
  )
})
const canExecute = computed(() => {
  return (
    proxy.$permission('scrapExportOrder:export') && infoList.data.status === 3
  )
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => modifyInfo.visible,
  (value) => {
    if (!value) {
      getMain()
      getList()
    }
  }
)

let obj = {
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('scrapExportOrder:price'),
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('scrapExportOrder:price'),
    show: false,
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('scrapExportOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  scrapReason: {
    label: '报废原因',
    value: 'scrapReason',
    minWidth: '150px',
    type: 'column',
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

function ifIndividualDetails(row) {
  return (
    infoList.data.isCargoSpaceManage === 0 ||
    (infoList.data.isCargoSpaceManage === 1 && row.status === 2) ||
    (infoList.data.isCargoSpaceManage === 1 && row.status === 3) ||
    (infoList.data.isCargoSpaceManage === 1 && row.status === 5)
  )
}
//提交
function submit() {
  // if(proxy.$store.state.permission.systemConfig.allow_scrap_export_approval == 2) {
    const params = {
      // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
      flowTaskCommentDto: { approvalType: 'submit' },
      processDefinitionKey: 'scrapExportCheck',
      orderId: infoList.data.id,
    }
    submitScrapExportOrder(params).then((res) => {
      if (res && res.success) {
        getDetails()
        ElMessage.success({
          message: '操作成功',
          duration: 3000,
          showClose: true,
        })
      } else {
        ElMessage.error({
          message: res.msg,
          duration: 3000,
          showClose: true,
        })
      }
    })
  //} else {
  //  let ids = []
  //  ids.push(infoList.data.id)
  //  submitScrapExportOrder(ids).then((resp) => {
  //    if (resp && resp.success) {
  //      refreshDetail()
  //    }
  //  })
  //}
}
function revoke() {
  let ids = []
  ids.push(infoList.data.id)
  revokeScrapExportOrder(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function doCancel() {
  scrapExportOrdersCancel(infoList.data.id).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
//取消拣货
function cancelDownTransfer() {
  proxy
    .$confirm('确认取消拣货吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let id = infoList.data.id
      scrapExportOrdersCancelDownShelf(id).then((resp) => {
        if (resp && resp.success) {
          refreshDetail()
        }
      })
    })
    .catch(() => {})
}
function scrapExport() {
  let ids = []
  ids.push(infoList.data.id)
  executeScrapExportOrder(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function refreshDetail() {
  getMain()
  getList()
}
function returnBack() {
  emit('returnBack', false)
}
function showDetail(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  individualInfo.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.tableRow ? props.tableRow.id : props.id,
    },
  }
  individualInfo.info = row
  individualInfo.visible = true
}
function getMain() {
  detailScrapExportOrder(props.tableRow ? props.tableRow.id : props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
    }
  })
}
function getList() {
  getScrapExportOrderDetailCustomizeListAll(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data
    }
  })
}

function update() {
  modifyInfo.orderId = infoList.data.id
  modifyInfo.title = '修改出库单'
  modifyInfo.visible = true
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'stockScrapDetail',
    deptId: infoList.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: props.tableRow ? props.tableRow.id : props.id,
            orderId: props.tableRow ? props.tableRow.id : props.id,
            orderNo: props.tableRow.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {
            customParam: JSON.stringify({
              ...filterInfo.query,
              // ...page.value,
              // page: dialogInfo.value.flag === 'page' ? true : false,
            }),
          },
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: props.tableRow ? props.tableRow.id : props.id,
      orderId: props.tableRow ? props.tableRow.id : props.id,
      orderNo: props.tableRow.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {
      customParam: JSON.stringify({
        ...filterInfo.query,
        // ...page.value,
        // page: dialogInfo.value.flag === 'page' ? true : false,
      }),
    },
  })
  popoverVisible.value = false
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderId: infoList.data.id,
      orderNo: infoList.data.orderNo,
      tempCode: 'stockScrapDetail',
      orderType: 8,
    })
  } catch (error) {}
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'scrapExportStoreDetail-com.slip.spd.entity.vo.stock.ScrapExportOrderDetailVO',
    orderIds: [props.tableRow ? props.tableRow.id : props.id],
  }
  getScrapExportPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('scrapExportOrder:price')
      )
    }
  })
}
//导出excel
function exportExcel() {
  exportExcelScrapExportOrder(filterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'scrapExportStoreDetail-com.slip.spd.entity.vo.stock.ScrapExportOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      getMain()
      getList()
    }
  })
}
function handleCancelAudit() {
  scrapExportOrderscancelAudit([infoList.data.id]).then((res) => {
    if (res && res.success) {
      getMain()
      getList()
    }
  })
}
function getFlowFormInfo() {
  return infoList.data
}
defineExpose({
  getFlowFormInfo
})
</script>

<style scoped></style>
